/*
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package net.javlov.vf;

import java.util.HashMap;
import java.util.Iterator;

import net.javlov.Option;
import net.javlov.State;

public class TracedQTable<T> implements QFunction<T> {

	private static final long serialVersionUID = 2877736348738619056L;

	protected QFunction<T> qfunc;
	
	protected HashMap<State<? extends T>, OptionTraces> traceTable;
	
	protected OptionTraces tracesTemplate;
	
	public TracedQTable(QFunction<T> qfunc, OptionTraces tracesTemplate) {
		this.qfunc = qfunc;
		traceTable = new HashMap<State<? extends T>, OptionTraces>(30);
		this.tracesTemplate = tracesTemplate;
	}
	
	@Override
	public double getValue(State<? extends T> s, Option<?> o) {
		return qfunc.getValue(s, o);
	}

	@Override
	public OptionValues getValues(State<? extends T> s) {
		return qfunc.getValues(s);
	}

	@Override
	public void init() {
		qfunc.init();
		traceTable.clear();
	}

	@Override
	public Double queryValue(State<? extends T> s, Option<?> o) {
		return qfunc.queryValue(s, o);
	}

	@Override
	public void reset() {
		qfunc.reset();
		traceTable.clear();
	}

	@Override
	public void setValue(State<? extends T> s, Option<?> o, double value) {
		qfunc.setValue(s, o, value);		
	}

	@Override
	public void update(State<? extends T> s, Option<?> o, double delta) {
		OptionTraces traces = traceTable.get(s);
		OptionTrace trace;
		if ( traces == null ) {
			traces = tracesTemplate.newInstance();
			addTrace(s, o, traces);
			traceTable.put(s, traces);
		} else {
			trace = traces.get(s, o);
			if ( trace == null )
				addTrace(s, o, traces);
			else
				trace.visit();
		}
		updateAll(s, o, delta);
	}
	
	protected void addTrace(State s, Option o, OptionTraces traces) {
		OptionTrace trace = tracesTemplate.newTrace();
		OptionValues vals = qfunc.getValues(s);
		trace.firstVisit(s, o, vals);
		traces.put(s, o, trace);
	}
	
	protected void updateAll(State<? extends T> s, Option o, double delta) {
		Iterator<OptionTraces> itr = traceTable.values().iterator();
		OptionTraces trs;
		while ( itr.hasNext() ) {
			trs = itr.next();
			if ( trs.updateAll(s, o, delta) )
				itr.remove();
		}
	}

}
